package com.ruoyi.verificationDetail.service.impl;

import java.util.Base64;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.distributionPoster.util.QRCodeGenerator;
import com.ruoyi.goodsDetail.service.IRemoteOrderGoodsDetailService;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.service.IRemoteOrderService;
import com.ruoyi.goodsDetail.domain.OrderGoodsDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.verificationDetail.mapper.VerificationDetailMapper;
import com.ruoyi.verificationDetail.domain.VerificationDetail;
import com.ruoyi.verificationDetail.domain.VerificationQRCodeRequest;
import com.ruoyi.verificationDetail.domain.VerificationQRCodeResult;
import com.ruoyi.verificationDetail.service.IVerificationDetailService;
import com.ruoyi.businessOrder.service.IBusinessOrderService;
import com.ruoyi.businessSku.service.IBusinessSkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 核销码明细信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-11-18
 */
@Service
public class VerificationDetailServiceImpl implements IVerificationDetailService
{
    private static final Logger log = LoggerFactory.getLogger(VerificationDetailServiceImpl.class);

    @Autowired
    private VerificationDetailMapper verificationDetailMapper;

    @Autowired
    private IBusinessOrderService businessOrderService;

    @Autowired
    private IBusinessSkuService businessSkuService;

    @Autowired
    private IRemoteOrderService remoteOrderService;

    // 要在原处增加说明
    @Autowired
    private IRemoteOrderGoodsDetailService remoteOrderGoodsDetailService;

    @Autowired
    private QRCodeGenerator qrCodeGenerator;

    @Value("${qrcode.base-url:https://maomingdongxinzhizun.cn}")
    private String qrCodeBaseUrl;

    @Value("${qrcode.expire-days:30}")
    private Integer qrCodeExpireDays;

    /**
     * 查询核销码明细信息
     *
     * @param detailId 核销码明细信息主键
     * @return 核销码明细信息
     */
    @Override
    public VerificationDetail selectVerificationDetailByDetailId(Long detailId)
    {
        return verificationDetailMapper.selectVerificationDetailByDetailId(detailId);
    }

    /**
     * 查询核销码明细信息列表
     *
     * @param verificationDetail 核销码明细信息
     * @return 核销码明细信息
     */
    @Override
    public List<VerificationDetail> selectVerificationDetailList(VerificationDetail verificationDetail)
    {
        return verificationDetailMapper.selectVerificationDetailList(verificationDetail);
    }

    /**
     * 新增核销码明细信息
     *
     * @param verificationDetail 核销码明细信息
     * @return 结果
     */
    @Override
    public int insertVerificationDetail(VerificationDetail verificationDetail)
    {
        verificationDetail.setCreateTime(DateUtils.getNowDate());
        return verificationDetailMapper.insertVerificationDetail(verificationDetail);
    }

    /**
     * 修改核销码明细信息
     *
     * @param verificationDetail 核销码明细信息
     * @return 结果
     */
    @Override
    public int updateVerificationDetail(VerificationDetail verificationDetail)
    {
        verificationDetail.setUpdateTime(DateUtils.getNowDate());
        return verificationDetailMapper.updateVerificationDetail(verificationDetail);
    }

    /**
     * 批量删除核销码明细信息
     *
     * @param detailIds 需要删除的核销码明细信息主键
     * @return 结果
     */
    @Override
    public int deleteVerificationDetailByDetailIds(Long[] detailIds)
    {
        return verificationDetailMapper.deleteVerificationDetailByDetailIds(detailIds);
    }

    /**
     * 删除核销码明细信息信息
     *
     * @param detailId 核销码明细信息主键
     * @return 结果
     */
    @Override
    public int deleteVerificationDetailByDetailId(Long detailId)
    {
        return verificationDetailMapper.deleteVerificationDetailByDetailId(detailId);
    }

    /**
     * 验证商品信息
     */
    private Order validateOrderInfo(Long orderId) {
        // 1. 验证订单的核销码是否存在
        Order order = remoteOrderService.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!"1".equals(order.getMasterStatus())) {
            throw new ServiceException("订单未支付");
        }
        if (order.getVerificationCode() == null) {
            throw new ServiceException("订单未生成核销码");
        }
        return order;
    }

    /**
     * 生成核销二维码
     */
    @Override
    public VerificationQRCodeResult generateVerificationQRCode(VerificationQRCodeRequest request) {
        try {
            log.info("开始生成核销二维码 - 订单ID: {}, 版本类型: {}, 时间戳: {}",
                    request.getOrderId(), request.getVersionType(), System.currentTimeMillis());

//            // 1. 验证请求参数
//            validateVerificationRequest(request);
            // 核销信息是在订单支付成功后创建的

            // 2. 获取订单信息, 并验证订单状态和核销码信息
            Order order = validateOrderInfo(request.getOrderId());

            // 3. 验证核销记录状态
            validateVerificationStatus(order);

            // 4. 生成二维码内容
            String qrContent = generateVerificationQRContent(order, request);
            log.info("生成二维码内容 - 订单ID: {}, 订单核销码: {}, 时间戳: {}",
                    request.getOrderId(), order.getVerificationCode(), System.currentTimeMillis());

            // 5. 生成场景ID用于唯一性检查
            String sceneId = generateVerificationSceneId(order);
            log.info("生成场景ID - 订单ID: {}, 时间戳: {}",
                    request.getOrderId(), System.currentTimeMillis());
//            // 6. 检查是否已存在相同scene_id的记录
//            Order existingOrder = checkExistingVerificationQRCode(sceneId);
//
//            if (existingOrder != null && StringUtils.isNotEmpty(existingOrder.getQrCodeUrl())) {
//                // 如果存在有效记录，直接返回现有结果
//                return buildVerificationQRCodeResult(existingOrder, qrContent, existingOrder.getQrCodeUrl());
//            }

            // 7. 生成二维码图片URL
            String qrCodeData = generateVerificationQRCodeImage(qrContent, request);
            log.info("生成二维码图片URL - 订单ID: {}, 时间戳: {}",
                    request.getOrderId(), System.currentTimeMillis());
            // 8. 更新核销记录的二维码信息
            Order orderResult = updateVerificationDetailWithQRCode(order, request, qrContent, qrCodeData, sceneId);
            log.info("更新核销记录的二维码信息 - 订单ID: {}, 时间戳: {}",
                    request.getOrderId(), System.currentTimeMillis());
            // 9. 返回结果
            return buildVerificationQRCodeResult(orderResult, qrContent, qrCodeData);

        } catch (Exception e) {
            log.error("生成核销二维码失败", e);
            throw new ServiceException("核销二维码生成失败：" + e.getMessage());
        }
    }

    /**
     * 验证核销二维码请求参数
     */
    private void validateVerificationRequest(VerificationQRCodeRequest request) {
        if (request.getDetailId() == null && request.getOrderId() == null) {
            throw new ServiceException("核销明细ID或订单ID必须提供");
        }
    }

    /**
     * 获取核销详情信息
     */
    private VerificationDetail getVerificationDetail(VerificationQRCodeRequest request) {
        VerificationDetail verificationDetail;
        if (request.getDetailId() != null) {
            verificationDetail = verificationDetailMapper.selectVerificationDetailByDetailId(request.getDetailId());
        } else {
            // 根据订单ID查询核销记录
            VerificationDetail query = new VerificationDetail();
            query.setOrderId(request.getOrderId());
            List<VerificationDetail> details = verificationDetailMapper.selectVerificationDetailList(query);
            if (details.isEmpty()) {
                throw new ServiceException("未找到对应的核销记录");
            }
            verificationDetail = details.get(0); // 取第一条记录
        }

        if (verificationDetail == null) {
            throw new ServiceException("核销记录不存在");
        }
        return verificationDetail;
    }

    /**
     * 验证核销记录状态
     */
    private void validateVerificationStatus(Order orderInfo) {
        if ("1".equals(orderInfo.getVerificationStatus())) {
            throw new ServiceException("该核销码已使用，无法生成二维码");
        }
        if ("2".equals(orderInfo.getVerificationStatus())) {
            throw new ServiceException("该核销码已过期");
        }

        // 检查有效期
//        Date now = new Date();
//        if (orderInfo.getValidEndTime() != null &&
//            orderInfo.getValidEndTime().before(now)) {
//            throw new ServiceException("核销码已过期");
//        }
    }

    /**
     * 生成核销二维码内容
     * 参考分销二维码和业务商品二维码的路径生成逻辑
     */
    private String generateVerificationQRContent(Order order,
                                               VerificationQRCodeRequest request) {
        StringBuilder contentBuilder = new StringBuilder();

        // 核销二维码格式：用于核销员扫码核销
        // https://maomingdongxinzhizun.cn/subpackageMall/pages/mall/verification/verScan?verificationCode=19D4960D61N84YQ

        if ("miniProgram".equals(request.getFormat()) || StringUtils.isEmpty(request.getFormat())) {
            // 小程序核销路径 - 按照您提供的配置格式
            contentBuilder.append(qrCodeBaseUrl);

            // 根据versionType添加对应的路径
            if ("test".equals(request.getVersionType())) {
                contentBuilder.append("/miniApp/verification/test");
            } else if ("development".equals(request.getVersionType())) {
                contentBuilder.append("/miniApp/verification/development");
            }

            contentBuilder.append("/subpackageMall/pages/mall/verification/verScan")
                    .append("?verificationCode=").append(order.getVerificationCode())
                    .append("&orderId=").append(order.getOrderId());

            if (request.getCustomParams() != null) {
                contentBuilder.append("&").append(request.getCustomParams());
            }
        } else {
            // H5核销链接
            contentBuilder.append(qrCodeBaseUrl)
                    .append("/verification/scan/")
                    .append("?verificationCode=").append(order.getVerificationCode())
                    .append("&orderId=").append(order.getOrderId());
        }

        return contentBuilder.toString();
    }

    /**
     * 生成核销场景ID
     */
    private String generateVerificationSceneId(Order order) {
        return "ver_" + order.getOrderId() +
               "_code_" + order.getVerificationCode();
    }

    /**
     * 检查是否已存在相同scene_id的核销二维码记录
     */
    private Order checkExistingVerificationQRCode(String sceneId) {
        // 这里可以根据需要实现更复杂的检查逻辑
        // 目前暂时返回null，每次重新生成
        return null;
    }

    /**
     * 生成核销二维码图片
     * 参考分销二维码和业务商品二维码的图片生成逻辑，生成Base64编码的图片数据
     */
    private String generateVerificationQRCodeImage(String qrContent, VerificationQRCodeRequest request) {
        // 获取二维码图片尺寸，默认为300x300
        Integer width = request.getWidth() != null ? request.getWidth() : 300;
        Integer height = request.getHeight() != null ? request.getHeight() : 300;

        // 确保尺寸在合理范围内（100-1000像素）
        width = Math.max(100, Math.min(1000, width));
        height = Math.max(100, Math.min(1000, height));

        try {
            // 生成二维码字节数组
            byte[] qrCodeBytes = qrCodeGenerator.generateQRCodeBytes(qrContent, width, height);

            // 将字节数组转换为Base64编码
            String base64Image = Base64.getEncoder().encodeToString(qrCodeBytes);

            // 返回Base64格式的图片数据，参考分销二维码的返回格式
            return "data:image/png;base64," + base64Image;

        } catch (Exception e) {
            log.error("生成核销二维码图片失败", e);
            throw new ServiceException("生成核销二维码图片失败: " + e.getMessage());
        }
    }

    /**
     * 更新订单中的核销记录的二维码信息
     * 优化字段映射，与分销二维码格式保持一致
     */
    private Order updateVerificationDetailWithQRCode(Order order, VerificationQRCodeRequest request,
                                                    String qrContent, String qrCodeData, String sceneId) {

        order.setSceneId(sceneId); // 存储二维码场景ID
        order.setQrCodeData(qrCodeData); // 存储Base64编码的图片数据
        order.setUpdateTime(new Date()); // 更新时间
        order.setUpdateBy(SecurityUtils.getUsername()); // 更新人

        // 更新订单信息
        int result = remoteOrderService.updateOrder(order);
        if (result <= 0) {
            throw new ServiceException("更新订单信息失败");
        }

        return order;
    }

    /**
     * 构建核销二维码结果
     * 优化结果格式，与分销二维码保持一致的返回结构
     */
    private VerificationQRCodeResult buildVerificationQRCodeResult(Order order,
                                                                  String qrContent, String qrCodeData) {
        // 构建结果对象
        VerificationQRCodeResult result = new VerificationQRCodeResult();

        result.setOrderId(order.getOrderId()); // 订单ID
        result.setOrderCode(order.getOrderCode()); // 订单编号
        // 获取商品信息
        OrderGoodsDetail detail = remoteOrderGoodsDetailService.selectOrderGoodsDetailByOrderId(order.getOrderId());
        if (detail == null) {
            throw new ServiceException("未找到商品订单信息");
        }
        result.setDetailId(detail.getDetailId()); // 商品订单ID
        result.setGoodsId(detail.getGoodsId()); // 商品ID
        result.setSkuId(detail.getSkuId()); // SKU ID

        result.setVerificationCode(order.getVerificationCode()); // 核销码
        result.setQrCodeData(qrCodeData); // 返回Base64编码的图片数据
        result.setQrContent(qrContent); // 核销二维码内容

        // 设置过期时间
        Date expireTime = DateUtils.addDays(new Date(), qrCodeExpireDays);
        result.setExpireTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", expireTime));

        result.setStatus("success");
        result.setMessage("核销二维码生成成功");
        return result;
    }
}
